import router from './router';
import store from './store';
import { getToken } from './utils/auth';
import { Notify } from 'quasar';

const writeList = ['/login', '/403', '/404'];

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();
  if (hasToken) {
    // console.log(1);
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      const currentUser = store.state.user.currentUser;

      const adminRole = currentUser.roles.find(item => {
        return item.name === 'ROLE_ADMIN';
      });

      if (adminRole) {
        next();
      } else {
        store.dispatch('user/logout');
        Notify.create({
          type: 'negative',
          message: '您无权登录',
          position: 'top'
        });
        next(`/login?redirect=${to.path}`);
      }
      // console.log(store.state.user.currentUser);
      // next();
    }
  } else {
    if (writeList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
